package com.bskj.sj.filter;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import com.alibaba.fastjson.JSONObject;
import com.bskj.common.utils.LogUtils;

public class RequestParameterWrapper extends HttpServletRequestWrapper {

	private Map<String, String[]> params = new HashMap<String, String[]>();

	public RequestParameterWrapper(HttpServletRequest request) {
		super(request);
		this.params.putAll(request.getParameterMap());
	}

	public RequestParameterWrapper(HttpServletRequest request,
			Map<String, Object> extraParams) {
		super(request);
		this.params.putAll(request.getParameterMap());
		addParameters(extraParams);
	}

	@Override
	public Map<String, String[]>  getParameterMap() {
		return this.params;
	}

	@Override
	public String[] getParameterValues(String name) {
		String[] results = params.get(name);
		if (results == null || results.length <= 0)
			return null;
		else {
			return results;
		}
	}
	@Override
	public Enumeration<String> getParameterNames() {
		Vector<String> vector = new Vector<String>(params.keySet());
		return vector.elements();
	}

	@Override
	public String getParameter(String name) {
		String[] results = params.get(name);
		if (results == null || results.length <= 0)
			return null;
		else {
			//java.net.URLDecoder.decode(results[0],"UTF-8");
			LogUtils.debug(JSONObject.toJSONString(results));
			return results[0];
		}
	}

	// 添加额外参数
	public void addParameters(Map<String, Object> extraParams) {
		for (Map.Entry<String, Object> entry : extraParams.entrySet()) {
			addParameter(entry.getKey(), entry.getValue());
		}
	}

	public void addParameter(String name, Object value) {
		if (value != null) {
			if (value instanceof String[]) {
				params.put(name, (String[]) value);
			} else if (value instanceof String) {
				params.put(name, new String[] { (String) value });
			} else {
				params.put(name, new String[] { String.valueOf(value) });
			}
		}
	}

}
